#include "qdeb822.h"

#include <QTextStream>

#include <QDebug>

#include <QJsonDocument>

QDeb822::QDeb822()
{

}

QVariant QDeb822::toVariant() const
{
    if (m_variants.isEmpty())
        return QVariant();

    if (m_variants.count() == 1)
        return m_variants.first();

    return m_variants;
}

QString QDeb822::toString() const
{
    return m_data;
}

QDeb822 QDeb822::fromVariant(const QVariant &variant)
{
    QDeb822 deb822;
    switch (variant.type()) {
    case QVariant::List:
        deb822.m_variants = variant.toList();
        break;
    case QVariant::Map:
    case QVariant::Hash:
        deb822.m_variants = QVariantList{variant};
        break;
    default:
        deb822.m_variants.clear();
        qDebug() << QObject::tr("不支持类型");
        break;
    }

    deb822.print();

    return deb822;
}

QDeb822 QDeb822::fromString(const QString &data)
{
    QDeb822 deb822;
    deb822.m_data = data;
    deb822.parse();
    return deb822;
}

QVariantMap QDeb822::toVariantMap(const QString &key)
{
    QVariantMap map;
    for (const QVariant &variant : m_variants) {
        const QVariantMap &section = variant.toMap();
        if (section.contains(key))
            map[section[key].toString()] = section;
    }
    return map;
}

void QDeb822::parse()
{
    for (const QString &paragraph : m_data.split("\n\n")) {
        if (paragraph.trimmed().isEmpty())
            continue;

        QVariantMap section;
        QString key;
        for (const QString &line : paragraph.split('\n')) {
            if (line == QStringLiteral(" .") || line == QStringLiteral("\t."))
                section[key] = section[key].toString().append('\n');
            else if (line.startsWith(' ') || line.startsWith('\t'))
                section[key] = section[key].toString().append(line.trimmed().prepend(' '));
            else if (line.startsWith('#'))
                qDebug() << QObject::tr("注释") << line;
            else if (line.contains(':')) {
                int index = line.indexOf(':');
                key = line.left(index);
                section[key] = line.mid(index + 1).trimmed();
            } else {
                qDebug() << QObject::tr("不支持数据") << line;
            }
        }

        if (!section.isEmpty())
            m_variants.append(section);
    }
}

void QDeb822::print()
{
    m_data.clear();
    QStringList paragraphs;
    for (const QVariant &variant : m_variants) {
        const QVariantMap &section = variant.toMap();
        QStringList paragraph;
        for (const QString &key : section.keys()) {
            QString value = section[key].toString();
            value.replace("\n\n", "\n.\n");
            value.replace('\n', "\n ");
            paragraph.append(QString("%1: %2").arg(key, value));
        }
        paragraphs.append(paragraph.join('\n'));
    }
    m_data = paragraphs.join("\n\n");
}
